/**
 * [一句话描述该类的功能]
 *
 * @author : [kai]
 * @version : [v1.0]
 * @createTime : [2022/10/28 18:31]
 */


package com.find.controller;

import com.find.controller.utils.R;
import com.find.domain.User;
import com.find.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags="登录功能")
@RequestMapping("/login")
public class LoginController {
    @Value("/^[\\u4E00-\\u9FA5a-zA-Z0-9_]{4,16}$/")
    String nameReg;
    @Autowired
    private UserService userService;
    @ApiOperation("登录功能")
    @ApiImplicitParam(name="user",value = "用户名与密码为必填项",required = true)
    @PostMapping
    public R login(@RequestBody User users
            , HttpServletRequest request, HttpServletResponse response)throws IOException {
        User user = userService.login(users.getName(),users.getPassword());
        if(user==null){
            response.setStatus(505);
            return new R(false,"登陆失败");
        }
        Cookie uidCookie = new Cookie("uid",user.getId().toString());
        uidCookie.setPath("/");
        uidCookie.setMaxAge(60*60*24*30);
        response.addCookie(uidCookie);
        Cookie cookie2 = new Cookie("name",user.getName());
        cookie2.setPath("/");
        cookie2.setMaxAge(60*60*24*30);
        response.addCookie(cookie2);
        Cookie cookie3 = new Cookie("Cookie",user.getName());
        cookie3.setPath("/");
        cookie3.setMaxAge(60*60*24*30);
        response.addCookie(cookie3);
        request.getSession().setAttribute("user",user);
        response.setStatus(200);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("password",user.getPassword());
        R r=new R(true,map);
        r.setData(user);
        return r;
    }
}
